<template>
	<div>
		<h2>头像修改</h2>
		<hr>
		<div style="display: flex;">
			<div style="width: 25%; height: 100%;">
				<h2>我的图片</h2>
				<div style="width: 10vm; height: 30vh;">
					<img v-bind:src="$ip + `/api/public/showimg/` + $store.state.user.pic"
						style="width: 100%; height: 100%;" />
				</div>
			</div>
			<div style="width: 74%; height: 100%;">
				<h2>上传新的图片</h2>
				请选择新的图片:<input type="file" ref="img" />
				<hr>
				<button @click="updateByPic"> 更新我的图片</button>
			</div>
		</div>
		{{ doadd }}
	</div>
</template>

<script>
export default {
	data() {
		return {
			token: "",
			doadd: ''
		}
	},
	methods: {
		updateByPic() {
			const fileInput = this.$refs.img;
			if (!fileInput.files.length) {
				alert("请选择一张图片");
				return;
			}

			const formData = new FormData();
			formData.append("mypic", fileInput.files[0]);

			this.$axios.post(this.$ip + "/api/user/updatePic", formData, {
				headers: { 'Authorization': this.token }
			})
				.then((response) => {
					this.doadd = response.data.msg;
					this.$store.commit('setUserPic', response.data.data);
					console.log(response.data.data);
				})
				.catch((error) => {
					console.error("更新图片:", error);
					alert("更新图片失败");
				});
		}
	},
	mounted() {
		this.token = window.localStorage.getItem("token");
	}
}
</script>

<style></style>